const app = getApp();

const RongIMLib = app.globalData.RongIMLib;
const RongIMEmoji = app.globalData.RongIMEmoji;


const src = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1550811235181&di=ed6d32826fdda6d72c991071e008cfc8&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01fd3e571dda8032f875a3996cb52f.jpg%402o.jpg";

var params = {
    appKey: "x18ywvqfxc6nc",
    self: null
};
Page({
    data: {
        auction_status: 0,		     // 活动状态 0 未开始 1 进行中 2 已结束 

        user_data: '',               // 用户微信端数据

        goodsDetail: '',             // 活动商品
        auction_id: "",            	 // 活动id
		auction_name:"",			 // 活动名称
        room_id: "",	             // 聊天室id

        goods_status: false,         // 活动状态 -  用户端查看
        auction_role: "",            // 活动 角色     0 : 普通用户  1 : 管理员  2 : 主持人 

        goods_id: "",                // 当前活动商品id

        chart_topper: "",            // 当前最高价用户
        purchaser: "",				 // 当前商品 拍中信息
        price: 0,                    // 加价金额

        price_status: 1,             // 当前竞拍方式

        entrust_price: "",           // 委托出价数据

        message: '',                 // 发送的消息
        toView: '',                  // 当前消息id
        last_sendTime:"",            // 上一条消息发送的时间
        last_content:"",             // 上一条消息发送的内容
        

        messageList: [],             // 消息记录

        emojiList: [],               // 表情数据

        customText: '',              // 自定义加价金额
        range: 10,                   // 加价范围

        auctionText: 1,              // 按钮状态   1 ： 开始拍卖  2 ： 开始倒计时  3 进入倒计时

        countDown: false,		 	 // 开始倒计时
        countDownTime: 10,		 	 // 倒计时时间

        scrollHeight: 0,
        keyboardHeight: 0,           // 键盘高度

        verbalTrickList: "",	     //话术数据列表
        verbalTrickShow: false,	     // 显示话术

        is_last: false,              // 是否是最后一件拍品
        last_goods: false,           // 最后一件商品是否已拍卖

        aution_is_end: false,        // 活动是否结束

        this_id: "",                 // 自己的用户id
        user_id: "",                 // 当前聊天对方用户id

        isAllowScroll: true,         // 是否加载中
        hasMsg: true,                // 是否有历史记录

        show_accredit: false,        // 显示授权
        is_phone_auth: false,        // 是否授权平台
        auction_phone_auth: false,   // 是否授权商家

        auction_margin: 0,           // 活动保证金
        now_margin: 0,               // 当前保证金

        auctionData:"",              // 团购数据
        groupList:[],                // 团购商品数据列表
        groupItem:"",                // 当前选中的团购商品
        groupIds:[],                 // 团购选中商品 id 
        groupAll:false,              // 全部取消选中
        groupTimer:null,             // 团购 倒计时
        auction_shutup:0,            // 活动禁言状态

		show_list:true,				 // 显示列表
        titleText:["起始价购买","封顶价购买","商品加价"],                 // 提示文字
        handleType:0,                // 购买方式
    },
    // 获取活动详情
    getGroupInfo(){
        var self = this;
        var url = '/index/bulkdetails';
        var auction_id = this.data.auction_id;
        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        id: auction_id
                    },
                    success: function (res) {
                        var datas = res.data;

                        if (datas.code == -1) {
                            self.loginOverdue();
                            return false;
                        }

                        if (datas.code == 1){
                            if (datas.data.auction.start_status == 1) {
                                self.countdownEvent(datas.data.auction.times)
                            }
                            self.getUserInfo();
                            self.setData({
                                auction_role: datas.data.auction.is_manage,                 // 用户状态
                                auction_shutup: datas.data.auction.ban_status,              // 活动是否禁言
                                auction_status: datas.data.auction.start_status,            // 活动开始状态
                                auctionData: datas.data.auction,                            // 活动信息
                                groupList: datas.data.goods,                                // 活动商品信息
                                is_phone_auth: datas.data.auction.is_phone_auth,            // 是否授权手机号给平台
                                auction_phone_auth: datas.data.auction.auction_phone_auth,  // 是否授权手机号给商家
                            })

                            if (!params.status) {
                                self.chatRoomRongIMLibInit();
                            }
                            wx.setNavigationBarTitle({ title: datas.data.auction.title || '开始拍卖' })
                            wx.hideLoading();
                        }else{
                            wx.hideLoading();
                        }
                        
                    }
                })
            },
        })       
    },
    // 页面加载 - 如果活动状态为未开始 - 执行
    // 页面加载 - 如果活动状态为已开始 - 执行倒计时
    countdownEvent(time){
        var self = this;
        var auction_status = this.data.auction_status

        var groupTimer = setInterval(function(){
            if (time){
                time--;
            }else{
                clearInterval(groupTimer);
                groupTimer = null;
                if ( auction_status == 0){      // 倒计时结束 活动开始

                }
                if ( auction_status == 1){      // 倒计时结束 活动结束
                    self.setData({
                        auction_status: 2
                    })
                }
            }
        },1000)
        this.setData({
            groupTimer: groupTimer
        })
    },
    // 选中商品
    changeGroupItem(e){
        var self = this;
        var goods_id = e.detail.value;
        this.setData({
            groupIds: goods_id
        })
    },
    // 查看详情
    goToDetail(e){
        let { currentTarget : { dataset : { id } } } = e;
        let { target : { dataset : { item } } } = e;
        if(item){return false}

        wx.navigateTo({
            url: `../trading-list/trading-list?id=${id}&type=look`,
        })
    },
    // 收起展开商品数据
    toggleList(e){
		var show_list = this.data.show_list;
		this.setData({
			show_list: !show_list
		})
    },
    // 确认购买信息
    verifyInfo(e){
        var type = e.target.dataset.type;
        this.setData({
            handleType:type
        })
        this.dialog_goods_info.showDialog();
    },
    // 加价 || 起始价 || 封顶价
    addPrice(e){
        var self = this;
        var handleType = this.data.handleType;
        var url = "/chatroom/start_price";
		var ids = this.data.groupIds ? this.data.groupIds.join(",") : "";
        var auction_id = this.data.auction_id;

		if (!ids){
			wx.showToast({
				image:"../../img/warning.png",
				title: '请选择藏品',
			})
			return false;
		}

        var is_phone_auth = this.data.is_phone_auth;
        var auction_phone_auth = this.data.auction_phone_auth;

        var now_margin = this.data.now_margin;
        var auction_margin = this.data.auction_margin;

        if (now_margin < auction_margin) {                      // 保证金不足
            this.dialog_margin.showDialog();
            return false;
        }

        if (!auction_phone_auth) {	// 未授权手机号
            this.setData({ show_accredit: true })
            return false;
        }

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id,
                        ids,
                        type: handleType
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) {
                            var list = [];
                            var names = [];
                            wx.showToast({ title: datas.msg, })
                            self.setData({
                                groupIds:[],
                                groupAll:false,
                            })
                            datas.data.map(function(item,index){
                                if ( item.type == 5 ){
                                    names.push(item.goods_num);
                                }else{
                                    if (item.type == 1 || item.type == 2) {         // 一口价成交 || 封顶价成交
                                        setTimeout(function(){
                                            sendCustomMessage('end', item)
                                        },100)
                                    }
                                    list.push(item);
                                }
                            })

                            if(list.length){            // 如果加价 或 购买成功 
                                sendMessagePrice(list);
                            }

                            if(names.join(",")){
                                wx.showModal({
                                    title: '温馨提示',
                                    content: "商品：" + names.join(",") + '已被抢购',
                                    success(res) {
                                        if (res.confirm) {
                                            console.log('用户点击确定')
                                        } else if (res.cancel) {
                                            console.log('用户点击取消')
                                        }
                                    }
                                })
                            }   

                            // if (datas.data.type == 1) {
                            //     // 成交订单
                            //     self.getLastrRaise();
                            // }
                        } else {
                            wx.showToast({
                                image: '../../img/warning.png',
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
    },
    // 商品操作提示框 - 取消
    __addPriceCancelEvent(){
        this.dialog_goods_info.hideDialog();
    },
    // 商品操作提示框 - 确认
    __addPriceEvent(){
        this.dialog_goods_info.hideDialog();
        this.addPrice();
    },


   
    // 输入消息
    inputMessage(e) {
        this.setData({ message: e.detail.value })
    },
    // 输入框失去焦点
    blurEvent(e) {
        this.setData({
            faceEmojiShow: false,
            verbalTrickShow: false,
        })
    },
    // 获取话术列表
    getVerbalTrick() {
        var self = this;
        var url = '/index/verblist';

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                    },
                    success: function (res) {
                        if (res.data.code == 1) {
                            self.setData({
                                verbalTrickList: res.data.data,
                            })
                        }
                    }
                })
            },
        })
    },
    // 显示表情列表
    showFaceEmoji() {
        var auction_shutup = this.data.auction_shutup;
        var auction_role = this.data.auction_role
        if (auction_shutup && auction_role != 2){
            return false;
        }
        this.setData({
            verbalTrickShow: false,
            faceEmojiShow: true
        })
    },
    // 选择表情
    selectFaceEmoj(e) {
        var self = this;
        var emoji = e.target.dataset.emoji;
        var message = this.data.message;
        this.setData({
            verbalTrickShow: false,
            message: message + emoji
        })
    },
    // 显示话术列表
    showVerbalTrick() {
        this.setData({
            faceEmojiShow: false,
            verbalTrickShow: true
        })
        this.getVerbalTrick()
    },
    // 选择话术
    selectVerbalTrick(e) {
        var self = this;
        var content = e.target.dataset.content;

        this.setData({
            verbalTrickShow: false,
            message: content,
        })
    },
    // 发送消息
    sendMessage(e) {
        var message = this.data.message;
        var auction_id = this.data.auction_id;
        var user_id = this.data.user_id;
        this.setData({
            faceEmojiShow: false,
            verbalTrickShow: false,
        })
        if (!message) {
            wx.showToast({
                image: '../../img/warning.png',
                title: '请输入内容',
            })
        } else {
            sendMessageChatRoom(message);
        }
    },
    // 禁言 
    shutUp() {
        this.dialog_shut_up.showDialog();
    },
    // 禁言 - 确认按钮
    __shutUpEvent() {
        var self = this;
        var url = "/chatroom/banned";
        var auction_id = this.data.auction_id;
        var auction_shutup = this.data.auction_shutup;
        this.dialog_shut_up.hideDialog();

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id,
                        type: +!auction_shutup,
                    },
                    success: function (res) {
                        if (res.data.code == 1) {
                            self.setData({
                                auction_shutup: +!auction_shutup
                            })
                            if (auction_shutup){        // 如果当前是禁言状态
                                console.log("解除禁言")
                                sendNotificationMessage("shutup",0)
                            }else{                      // 如果当前不是禁言状态
                                sendNotificationMessage("shutup", 1)
                                console.log("全体禁言")
                            }
                        }
                    }
                })
            },
        })
        
    },
    // 禁言 - 取消按钮
    __shutUpCancelEvent() {
        this.dialog_shut_up.hideDialog();
    },
    onLoad: function (options) {
        wx.showLoading({
            title: '加载中',
            mask:true
        })
        var self = this;
        params.room_id = options.id ? "chatRoomId" + options.id : "chatRoomId146";    // 聊天室id
        params.self = this;

        this.dialog_phone = this.selectComponent("#dialog-phone");                  // 未授权手机号提示
        this.dialog_shut_up = this.selectComponent("#dialog-shut-up");              // 禁言提示
        this.dialog_open = this.selectComponent("#dialog-open");                    // 解除禁言提示 
        this.dialog_margin = this.selectComponent("#dialog-margin");                // 保证金提示
        this.dialog_goods_info = this.selectComponent("#dialog-goods-info");        // 商品操作提示
        

        this.login = this.selectComponent("#login");                                // 授权登录
        this.phone = this.selectComponent("#phone");                                // 授权手机号

        this.setData({
            auction_id: options.id || "",
			auction_name: options.name
        })

        this.chatRoomLoginLoad()
    },

    // 分享触发*******************************************************************************************************************

    onShareAppMessage(options) {
        var auction_id = this.data.auction_id;
        var auction_name = this.data.auction_name || this.data.auctionData.title;
        if (options.form == "button") {
            console.log("来自按钮")
        }
        return {
			title: '团购活动：' + auction_name,
			path: `/pages/my-group-chat-room/my-group-chat-room?id=${auction_id}&name=${auction_name}`
        }
    },
    // 聊天室 - 登录后加载数据
    chatRoomLoginLoad() {
        var self = this;
        wx.getStorage({
            key: 'user',
            success: function (res) {
                console.log("已登录")
                self.getGroupInfo();
            },
            fail() {
                console.log("未登录")
                wx.login({
                    success: res => {
                        wx.request({
                            url: app.url.requestUrl + '/login/login',
                            method: 'POST',
                            data: {
                                code: res.code
                            },
                            success: function (data) {
                                var datas = data.data;
                                if (data.data.code == 1) {
                                    wx.setStorage({
                                        key: 'user',
                                        data: data.data.data
                                    })
                                    self.getGroupInfo();
                                }
                            }
                        })
                    }
                })
            }
        })
    },
	// 显示页面
	onShow(){
        if (params.status){
            joinChatRoom();
        }
	},
    // 卸载页面
    onUnload() {
        var self = this;
        console.log("卸载页面吧" + params.room_id)
        var chatRoomId = params.room_id; // 聊天室 Id。
        var groupTimer = this.data.groupTimer
        if (params.room_id) {
            RongIMLib.RongIMClient.getInstance().quitChatRoom(chatRoomId, {
                onSuccess: function () {
                    console.log("退出聊天室成功")
                    clearInterval(groupTimer)
                    params.status = false;
                    params.self.setData({
                        messageList: [],
                    })
                },
                onError: function (error) {
                    console.log("退出聊天室失败")
                }
            });
        }
    },
    // 切换 显示 隐藏 授权弹窗
    toggleAccredit() {
        var show_accredit = this.data.show_accredit;
        this.setData({ show_accredit: !show_accredit })
    },
    // 获取用户手机号
    getUserPhone() {
        var is_phone_auth = this.data.is_phone_auth;
        var auction_phone_auth = this.data.auction_phone_auth;

        if (!is_phone_auth) {
            this.phone.showModalBox();
        } else {
            this.accredit();
        }
    },
    // 登录授权
    getUserInfo() {
        var self = this;
        //获取用户信息
        wx.getSetting({
            success: res => {
                if (!res.authSetting['scope.userInfo']) {
                    this.login.showModalBox()
                } else {
                    //已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getStorage({
                        key: 'user_info',
                        success(res) {
                            self.setData({
                                user_data: res.data
                            })
                        },
                        fail() {
                            wx.getUserInfo({
                                success(res) {
                                    self.uploadUserInfo(res.userInfo);
                                }
                            })
                        }
                    })
                }
            }
        })
    },
    // 授权手机号
    __accreditPhoneEvent(e) {
        if (e.detail.errMsg == 'getPhoneNumber:user deny') {
            wx.showToast({
                image: '../../img/warning.png',
                title: '未同意授权',
            })
        } else {
            wx.showLoading({ title: '授权中...' })
            this.decodePhone(e.detail.phone);
            this.phone.hideModalBox();
        }
    },
    // 解码手机号
    decodePhone(data) {
        var self = this;
        var url = "/chatroom/authPhone";

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        session_key: res.data.session_key,
                        encryptedData: data.encryptedData,
                        iv: data.iv
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) {
                            self.accredit();
                        } else {
                            wx.showToast({
                                image: "../../img/warning.png",
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
    },
    accredit() {
        var self = this;
        var url = "/chatroom/auth_auction_phone";
        var auction_id = this.data.auction_id;

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) {
                            wx.showToast({
                                title: '授权手机号成功',
                            })
                            self.setData({
                                is_phone_auth: 1,
                                auction_phone_auth: 1,
                                show_accredit: false
                            })
                        } else {
                            wx.showToast({
                                image: "../../img/warning.png",
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
    },


  // formid
  formSubmit: function (e) {
    var formId = e.detail.formId

    var that = this;
    wx.getStorage({
      key: 'user',
      success: function (res) {
        wx.request({
          url: app.url.requestUrl + '/user/collect_formid',
          method: 'POST',
          data: {
            openid: res.data.openid,
            token: res.data.token,
            formid: formId
          },
          success: function (res) {
            if (res.data.code == 1) {

            }
          }
        })
      }
    })
  },

    // 确认授权登录
    __accreditEvent(e) {
        this.uploadUserInfo(e.detail.user_info)
        this.login.hideModalBox()
    },
    // 登录成功上传头像及用户信息
    uploadUserInfo(info) {
        var self = this;
        var url = "/user/save_user_info";
        var name = info.nickName;
        var header_img = info.avatarUrl

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        name,
                        header_img
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) { 
                            wx.setStorage({
                                key: 'user_info',
                                data: info,
                            })
                            self.setData({
                                user_data: info
                            })
                        }
                    }
                })
            }
        })
    },
    // 初始化融云
    chatRoomRongIMLibInit() {
        var self = this;
        joinChatRoom()
    },
    // 保证金不足 - 确认
    __marginEvent() {
        this.dialog_margin.hideDialog();
        wx.navigateTo({
            url: '../my-recharge/my-recharge?type=margin&charge_type=2',
        })
    },
    // 保证金不足 - 取消
    __marginCancelEvent() {
        this.dialog_margin.hideDialog();
    },
    // 改变聊天室状态
    changeGoodsStatus(type) {
        var self = this;
        var url = "/chatroom/change_goods_status";
        var goods_id = this.data.goodsDetail.id;
        var auction_id = this.data.auction_id;
        var is_last = this.data.is_last;
        var last_goods = this.data.last_goods;

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        goods_id,
                        auction_id,
                        type: type,
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 0) {
                            wx.showToast({
                                image: '../../img/warning.png',
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
        if (is_last && (type == -1 || type == 2)) {
            this.endAuction();
        }
    },
    // 创建聊天室
    foundChatRoom() {
        var url = "/chatroom/create_chatroom";
        var auction_id = this.data.activeify_id
        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id: auction_id
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 0) {
                            wx.showToast({
                                image: '../../img/warning.png',
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
    },
    // 登录过去状态
    loginOverdue(e) {
        var self = this;
        wx.removeStorage({
            key: 'user',
            success: function (res) {
                self.chatRoomLoginLoad();
            },
        })
    },
    changeRongIMStatus(status) {
        wx.setStorage({
            key: 'RongIM_S',
            data: status,
        })
    },
    // 结束当前活动
    endAuction() {
        var self = this;
        var url = "/chatroom/start_auction";
        var auction_id = this.data.auction_id;

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id: auction_id,
                        type: -1
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) {
                            sendCustomMessage(self, "auctionEnd")
                        } else if (datas.code == 0) {
                            wx.showToast({
                                image: '../../img/warning.png',
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
    },
    // 下拉获取历史记录
    getHistoryList() {
        var hasMsg = this.data.hasMsg;
        if (hasMsg) {
            this.setData({ isAllowScroll: true })
            getHistoryList(5);
        } else {
            this.setData({ isAllowScroll: false })
        }
    },
    onReady(){
        
    }
})

// 加入聊天室
function joinChatRoom() {
    var chatRoomId = params.room_id;       // 聊天室 Id
    var count = 20;             // 拉取最近聊天最多 50 条
    
    RongIMLib.RongIMClient.getInstance().joinChatRoom(chatRoomId, count, {
        onSuccess: function (message) {
            app.globalData.writeInContent = writeInContent;
            app.globalData.writeInMaterial = writeInMaterial;
            app.globalData.writeInNotification = writeInNotification;
            app.globalData.writeInAuctionStatus = writeInAuctionStatus;
            app.globalData.writeSettlementMessage = writeSettlementMessage;
            // 加入聊天室成功。
            params.status = true;
            console.log('加入聊天室成功。' + chatRoomId);
        },
        onError: function (error) {
            // 加入聊天室失败
            console.log('加入聊天室失败。');
        }
    });
    // 获取表情
    getEmojiList()
}

// 获取 emoji 表情数据
function getEmojiList() {
    var list = RongIMEmoji.list;
    var horizontal = 8;
    var vertical = 3;
    var length = -1;
    var emojiList = [];

    list.map(function (item, index) {
        if (index % (horizontal * vertical) == 0) {
            length++;
            emojiList[length] = [];
        }
        emojiList[length].push(item)
    })
    params.self.setData({
        emojiList: emojiList,
    })
}

// 发送文本消息
function sendMessageChatRoom(text) {
    var chatRoomId = params.room_id;
    var extra = {
        nickname: params.self.data.user_data.nickName,
        photo: params.self.data.user_data.avatarUrl,
        data_type: "text"
    }

    var msg = new RongIMLib.TextMessage({ content: text, extra: extra });
    var conversationType = RongIMLib.ConversationType.CHATROOM;
    
    var last_sendTime = params.self.data.last_sendTime;
    var last_content = params.self.data.last_content;
    var now_time = new Date().getTime();

    if (now_time - last_sendTime <= 15000 && text == last_content) {
        wx.showToast({
            image: "../../img/warning.png",
            title: '请勿重复发送',
        })
        return false;
    }

    RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, chatRoomId, msg, {
        onSuccess: function (message) {
            var messageList = params.self.data.messageList;                // 消息数据列表
            //messageUId 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
            
            messageList.push({
                messageType: 'text',
                content: message.content.content,
                userInfo: {
                    user_id: message.senderUserId,
                    nickname: message.content.extra.nickname || '一位不愿透露姓名的网友',
                    photo:message.content.extra.photo || src,
                    data_type: 'text',
                },
                messageUId: message.messageUId
            })

            messageList = isRepeat(messageList, "messageUId");

            params.self.setData({
                message: '',
                toView: message.messageUId,
                last_sendTime: now_time,
                last_content:text,
                messageList: messageList,
            })

            console.log("发送文本消息成功");
        },
        onError: sendError
    })
}

// 发送加价消息
function sendMessagePrice(info) {
	var chatRoomId = params.room_id;
	var extra = {
		nickname: params.self.data.user_data.nickName,
		photo: params.self.data.user_data.avatarUrl,
		info: info,
        data_type:"price"
	}

	var msg = new RongIMLib.TextMessage({ extra: extra });
	var conversationType = RongIMLib.ConversationType.CHATROOM;
	RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, chatRoomId, msg, {
		onSuccess: function (message) {
            var messageList = params.self.data.messageList;                // 消息数据列表
            var groupList = params.self.data.groupList;  				   // 商品数据列表
			//message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
            messageList.push({
				messageType: 'text',
				userInfo: {
					user_id: message.senderUserId,
					nickname:message.content.extra.nickname || '一位不愿透露姓名的网友',
					photo:message.content.extra.photo || src,
					data_type: 'price' ,
					info:message.content.extra.info		// 加价信息
				},
				messageUId: message.messageUId
			})
			
			message.content.extra.info.map(function(item,index){
				for (var i=0;i<groupList.length;i++){
					if (groupList[i].id == item.id){
                        if (item.type == 1 || item.type == 2) {
                            groupList[i].auction_status = 2
                        }
						groupList[i].current_price = item.price;
                        groupList[i].choice = 0;
                        groupList[i].range = item.range;
					}
				}
			})

            messageList = isRepeat(messageList, "messageUId");

            params.self.setData({
                message:"",
                toView: message.messageUId,
                groupList,
                messageList: messageList,
            })

			console.log("发送竞价消息成功");
		},
        onError: sendError
	})
}

// 发送倒计时
function sendCountDown(self, text) {
    var chatRoomId = params.room_id;
    var msg = new RongIMLib.TextMessage({ content: text, extra: { data_type: 'countDown' } });
    var conversationType = RongIMLib.ConversationType.CHATROOM;
    
    RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, chatRoomId, msg, {
        onSuccess: function (message) {
            var messageList = self.data.messageList;                // 消息数据列表

            //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
            messageList.push({
                messageType: 'countDown',
                content: message.content.content,
                messageUId: message.messageUId
            })

            messageList = isRepeat(messageList, "messageUId");

            params.self.setData({
                toView: message.messageUId,
                messageList: messageList,
            })

            console.log("发送倒计时成功");
        },
        onError: sendError
    })
}

//发送自定义消息 资料 - 开始竞拍 - 结束竞拍
function sendCustomMessage(text,info) {
    var chatRoomId = params.room_id;
    if (text == "auctionStart") {   // 活动开始
        var extra = {
            data_type: text,
        }
    }
    if (text == "start") {          // 竞拍开始
        var extra = {
            data_type: text,
            data: params.self.data.goodsDetail
        }
    }
    if (text == "end") {            // 竞拍结束
        var extra = {
            data_type: text,
            nickname: params.self.data.user_data.nickName,
            info: info || {}
        }
    }
    if (text == "auctionEnd") {     // 活动结束
        var extra = {
            data_type: text,
        }
    }
       
    var msg = new RongIMLib.ProfileNotificationMessage({ content: text, extra: extra });
    var conversationType = RongIMLib.ConversationType.CHATROOM;
    
    var last_sendTime = params.self.data.last_sendTime;
    var last_content = params.self.data.last_content;
    var now_time = new Date().getTime();

    if (now_time - last_sendTime <= 15000 && text == last_content) {
        wx.showToast({
            image: "../../img/warning.png",
            title: '请勿重复发送',
        })
        return false;
    }

    RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, chatRoomId, msg, {
        onSuccess: function (message) {
            var messageList = params.self.data.messageList;                            // 消息数据列表
            
            if (message.content.extra.data_type == "auctionStart") {
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                })
            }
            if (message.content.extra.data_type == "start") {
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                    content: {
                        index: message.content.extra.data.index || 0,
                        title: message.content.extra.data.title,
                        goods_id: message.content.extra.data.goods_id,
                    }
                })
            }
            if (message.content.extra.data_type == "end") {
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                    content: {
                        data_type: message.content.extra.info.type,
                        price: message.content.extra.info.price,
                        goods_id: message.content.extra.info.goods_id,
                        nickname: message.content.extra.nickname,
                        cname: message.content.extra.info.goods_num,
                    }
                })
            }
            if (message.content.extra.data_type == "auctionEnd") {
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                })
            }

            messageList = isRepeat(messageList, "messageUId");

            params.self.setData({
                toView: message.messageUId,
                last_sendTime: now_time,
                last_content: text,
                messageList: messageList,
            })
        },
        onError: sendError
    })
}

// 发送通知消息
function sendNotificationMessage(type,value){
    var chatRoomId = params.room_id;

    var extra = {
        data_type: type,
        value: value
    }

    var msg = new RongIMLib.InformationNotificationMessage({ extra: extra });
    var conversationType = RongIMLib.ConversationType.CHATROOM;

    var last_sendTime = params.self.data.last_sendTime;
    var last_content = params.self.data.last_content;
    var now_time = new Date().getTime();

    if (now_time - last_sendTime <= 15000 && text == last_content) {
        wx.showToast({
            image: "../../img/warning.png",
            title: '请勿重复发送',
        })
        return false;
    }

    RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, chatRoomId, msg, {
        onSuccess: function (message) {
            console.log(message)
            var messageList = params.self.data.messageList;                            // 消息数据列表
            if (message.content.extra.data_type == "shutup") {          // 如果是禁言通知
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                    content: {
                        value : message.content.extra.value
                    }
                })
            }

            messageList = isRepeat(messageList, "messageUId");

            params.self.setData({
                toView: message.messageUId,
                last_sendTime: now_time,
                last_content: text,
                messageList: messageList,
            })

        },
        onError: sendError
    })
}


// 写入文本消息
var writeInContent = function (num, message) {
    console.log(message)
    var messageList = params.self.data.messageList;                 // 消息数据列表
    var groupList = params.self.data.groupList;  				    // 商品数据列表
    // message.content.content => 消息内容
    if (message.content.extra && message.content.extra.data_type == 'price' && params.self.data.countDown) {
        params.self.setData({
            goods_status: true,
            countDown: false,
        })
    }
    if (message.content.extra) {
        if (message.content.extra.data_type == 'text') {
            // 文本消息 || 加价消息
            messageList.push({
                messageType: 'text',
                content: message.content.content,
                userInfo: {
                    user_id: message.senderUserId,
                    nickname: message.content.extra.nickname || '一位不愿透露姓名的网友',
                    photo: message.content.extra.photo || src,
                    data_type: 'text',
                    range: message.content.range || 10
                },
                messageUId: message.messageUId
            })
        }
        if (message.content.extra.data_type == 'price') {
            messageList.push({
                messageType: 'text',
                userInfo: {
                    user_id: message.senderUserId,
                    nickname: message.content.extra.nickname || '一位不愿透露姓名的网友',
                    photo: message.content.extra.photo || src,
                    data_type: 'price',
                    info: message.content.extra.info
                },
                messageUId: message.messageUId
            })
            message.content.extra.info.map(function (item, index) {
                for (var i = 0; i < groupList.length; i++) {
                    if ( groupList[i].id == item.id ) {
                        if(item.type == 1 || item.type == 2){
                            groupList[i].auction_status = 2
                        }
                        if (groupList[i].current_price < item.price){
                            groupList[i].current_price = item.price
                        }
                        if (groupList[i].top_price == groupList[i].current_price) {
                            groupList[i].choice = 0 
                        }
                    }
                }
            })
            params.self.setData({
                groupList
            })
        } 
        if (message.content.extra.data_type == "countDown") {
            messageList.push({
                messageType: 'countDown',
                content: message.content.content,
                messageUId: message.messageUId
            })
            if (message.content.content <= 2) {
                params.self.setData({
                    goods_status: false
                })
            }
        }
    } 

    messageList = isRepeat(messageList, "messageUId");

    params.self.setData({
        toView: message.messageUId,
        messageList: messageList,
    })

}
// 写入资料消息 
var writeInMaterial = function (num, message) {

    var messageList = params.self.data.messageList;                 // 消息数据列表

    if (message.content.extra.data_type == "auctionStart") {    // 如果是开始活动
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId,
        })

        params.self.setData({
            auction_status:1
        })
    }
    
    if (message.content.extra.data_type == "start") {           // 如果是开始竞拍
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId,
            content: {
                title: message.content.extra.data.title,
                goods_id: message.content.extra.data.goods_id
            }
        })
    }
    
    if (message.content.extra.data_type == "end") {             // 如果是结束竞拍
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId,
            content: {
                data_type: message.content.extra.info.type,
                price: message.content.extra.info.price,
                goods_id: message.content.extra.info.goods_id,
                nickname: message.content.extra.nickname,
                cname: message.content.extra.info.goods_num,
            }
        })
    }
    
    if (message.content.extra.data_type == "repeal") {          // 如果是撤销竞拍
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId,
            content: {
                goods_id: message.content.extra.data.goods_id,
                title: message.content.extra.data.title,
            }
        })
        if (!params.self.data.aution_is_end) {
            params.self.getNowGoodsData();
        }
    }
   
    if (message.content.extra.data_type == "auctionEnd") {      // 如果是活动结束
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId,
        })
        params.self.setData({
            goods_status: false,
            auctionText: 0,
        })
    }

    messageList = isRepeat(messageList, "messageUId");

    params.self.setData({
        toView: message.messageUId,
        messageList: messageList,
    })

}
// 写入通知消息
var writeInNotification = function (num,message){

    var messageList = params.self.data.messageList;                 // 消息数据列表
    if (message.content.extra.data_type == "shutup") {          // 如果是禁言通知
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId,
            content: {
                value: message.content.extra.value
            }
        })
    }

    messageList = isRepeat(messageList, "messageUId");

    params.self.setData({
        toView: message.messageUId,
        messageList: messageList,
        auction_shutup: message.content.extra.value
    })

}

// 写入后台发送的系统消息
var writeInAuctionStatus = function (num, message) {

    var messageList = params.self.data.messageList;

    if (message.content.message.content.data_type == "auctionStart") {            // 如果是开始活动
        messageList.push({
            messageType: message.content.message.content.data_type,
            messageUId: message.messageUId,
        })
        params.self.getGroupInfo();
    }

    if (message.content.message.content.data_type == "auctionEnd") {              // 如果是活动结束
        messageList.push({
            messageType: message.content.message.content.data_type,
            messageUId: message.messageUId,
        })
        params.self.getGroupInfo();
    }
    messageList = isRepeat(messageList, "messageUId");

    params.self.setData({
        toView: message.messageUId,
        messageList: messageList,
    })
}

// 写入订单消息
var writeSettlementMessage = function( num , message ){
    var messageList = params.self.data.messageList;

    messageList.push({
        messageType: 'settlement',
        content: message.content.message.content,
        messageUId: message.messageUId
    })
    messageList = isRepeat(messageList, "messageUId");

    console.log(messageList)
    params.self.setData({
        toView: message.messageUId,
        messageList: messageList
    })
}


/*  融云接收消息会出现重复 message  暂未找出解决方法，先作去重处理
 *  方法一：判断聊天消息是否有重复 如果这个方法不行 就只能用去重了... 
 *  arr :   数据列表
 *  key :   指定比对两条数据的 key 值
 */
function isAdjacent(arr, key) {
    var len = arr.length;
    if (len < 2) {                                  // 是否只有一条数据
        return true;
    }
    if (arr[len - 1][key] == arr[len - 2][key]) {   // 判断当前这条消息 是否和上一条消息重复
        return false;
    }
    return true;
}


/*方法二 ：判断JSON数组是否有重复*/
function isRepeat(arr, key) {
    var hash = {};
    for (var i in arr) {
        if (hash[arr[i][key]]) {
            return distinctList(arr, key);
        } //hash 哈希
        hash[arr[i][key]] = true;
    }
    return arr;
}

/* 聊天消息去重
 *  array : 需要去重的数组
 *  key   : 指定 key 值 ， 根据该 key 值执行去重
 */
function distinctList(array, key) {
    var result = [array[0]];
    for (var i = 1; i < array.length; i++) {
        var item = array[i];
        var repeat = false;
        for (var j = 0; j < result.length; j++) {
            if (item[key] == result[j][key]) {
                repeat = true;
                break;
            }
        }
        if (!repeat) {
            result.push(item);
        }
    }
    return result;
}



// 发送消息错误回调
var sendError = function (errorCode, message) {
    var info = '';
    switch (errorCode) {
        case RongIMLib.ErrorCode.TIMEOUT:
            info = '超时';
            break;
        case RongIMLib.ErrorCode.UNKNOWN:
            info = '未知错误';
            break;
        case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
            info = '在黑名单中，无法向对方发送消息';
            break;
        case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
            info = '不在讨论组中';
            break;
        case RongIMLib.ErrorCode.NOT_IN_GROUP:
            info = '不在群组中';
            break;
        case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
            info = '不在聊天室中';
            break;
        default:
            info = x;
            break;
    }
    wx.showToast({
        image: '../../img/warning.png',
        title: '发送失败:' + info
    })

}